package com.own.component.store.redis.method;

import com.own.component.store.core.method.base.BaseStore;
import org.redisson.api.RedissonClient;

import java.time.Duration;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * DefaultBaseStoreMethod
 *
 * @author chenxueli
 * @date 2024-05-15 11:34:00
 */
public abstract class DefaultBaseStoreMethod implements BaseStore {

    private final RedissonClient redissonClient;

    public DefaultBaseStoreMethod(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 获取 redisson 客户端
     *
     * @return redisson 客户端
     */
    protected RedissonClient getRedissonClient() {
        return redissonClient;
    }

    /**
     * 是否存在值
     *
     * @param key key
     * @return 是否存在
     */
    @Override
    public boolean contains(String key) {
        return redissonClient.getBucket(buildKey(key)).isExists();
    }

    /**
     * 获取所有的key
     *
     * @return 所有的key
     */
    @Override
    public Set<String> keySet() {
        return redissonClient.getKeys().getKeysStreamByPattern(buildKey(type()) + "*").collect(Collectors.toSet());
    }

    /**
     * 删除原子值
     *
     * @param name 保存的name
     */
    @Override
    public void remove(String name) {
        redissonClient.getBucket(buildKey(name)).delete();
    }

    /**
     * 设置超时时间
     *
     * @param key      key
     * @param duration 超时时间
     */
    @Override
    public void expire(String key, Duration duration) {
        redissonClient.getAtomicLong(buildKey(key)).expire(duration);
    }

    /**
     * 匹配key
     *
     * @param pattern 匹配规则
     * @return keyList
     */
    @Override
    public Set<String> pattern(String pattern) {
        var key = buildKey(type());
        return redissonClient.getKeys().getKeysStreamByPattern(key + pattern)
                .map(item -> item.replaceFirst(key, ""))
                .collect(Collectors.toSet());
    }

}
